/**
 * user 业务处理层, 可能会调用多表的查询，调用多个Model接口
 */
const md5 = require('md5');
const User = require('../model/user.js');
const Base64 = require('js-base64').Base64;
const ApiErrorNames = require('../config/ApiErrorNames.js');
const APIError = require('../middlewares/result.js').APIError;

/**
 * 查询所有用户
 */
let findAllUser = async () => {
  let user = await User.findAllUser();
  //把results对象转为字符串，去掉RowDataPacket
  user = JSON.stringify(user);
  //把results字符串转为json对象  格式---[{}]
  user = JSON.parse(user);
  return user;
};

/**
 * 根据用户id查询
 */
let findUserById = async (userId) => {
  let user = await User.findUserById(userId);
  //把results对象转为字符串，去掉RowDataPacket
  user = JSON.stringify(user);
  //把results字符串转为json对象  格式---[{}]
  user = JSON.parse(user);
  return user;
};

/**
 * 用户登录
 */
let checkLogin = async (value) => {
  let name = value.name || '';
  let phone = value.phone || '';
  // 检查此手机号的用户
  phone = Base64.encode(md5(phone));
  let user = await User.findUserByPhone(phone);
  //把results对象转为字符串，去掉RowDataPacket
  user = JSON.stringify(user);
  //把results字符串转为json对象  格式---[{}]
  user = JSON.parse(user);
  if (!user) {
    throw new APIError(ApiErrorNames.USER_NOT_EXIST);
  }
  if (name !== user.name) { // 1. 姓名错误 2. 换微信了  --> 提示修名或者重新注册
    throw new APIError(ApiErrorNames.USER_ERROR);
  }

  return {
    ...user,
  };
};

/**
 * 注册用户
 * @param {*} value
 */
let addUser = async (value) => {
  let name = value.name || '';
  let phone = value.phone || '';
  // 检查用户名是否为空
  if (!name) {
    throw new APIError(ApiErrorNames.USERNAME_EMPTY);
  }
  //检查密码是否为空
  if (!phone) {
    throw new APIError(ApiErrorNames.PHONE_EMPTY);
  }
  //手机号Md5加密 base64编码
  phone = Base64.encode(md5(phone));
  
  // 手机号唯一性检查  user为数组
  let existPhone = await User.findUserByPhone(phone);
  if (existPhone) {
    throw new APIError(ApiErrorNames.PHONE_EXIST);
  }
  // 随机生成userId
  const userId = new Date().getTime() + Math.floor(Math.random() * 1000);
  await User.addUserData({...value, phone, userId: `${userId}`});
  let theUser = await User.findUserByPhone(phone);
  return theUser;
};

/**
 * 更新用户信息
 */
const updateUserDataByUserId = async (data) => {
  const result = await User.updateUserDataByUserId({...data});
  return result;
};


module.exports = {
  checkLogin,
  addUser,
  findAllUser,
  findUserById,
  updateUserDataByUserId,
};
